<?php
class imgUpload_controller extends common {
	const allowedExts = array("gif", "jpeg", "jpg", "png");
	function index() {
		$temp = explode(".", $_FILES["file"]["name"]);
		$ext  = end($temp);
		if (!in_array($_FILES["file"]["type"], array(
			"image/gif",
			"image/jpeg",
			"image/jpg",
			"image/pjpeg",
			"image/x-png",
			"image/png"
		)) || !in_array($ext, self::allowedExts))
			return msg(1, '不支持的文件类型！');
		
		if ($_FILES["file"]["size"] >= 10 * 1024 * 1024)
			return msg(2, "文件大小不能超过10M！");
		
		if ($_FILES["file"]["error"] > 0)
			return msg(3, "文件错误！");
		
		$post_data = array(
			"image" => new CURLFile(realpath($_FILES['file']['tmp_name']))
		);
		$data      = $this->Curl_POST("https://graph.baidu.com/upload", $post_data);
		if ($data == "") {
			return msg(4, "上传失败！");
		} else if (!($obj = json_decode($data)) || $obj->msg !== "Success" || !$obj->data->sign) {
			return msg(5, "上传失败！");
		} else {
			$pic = "https://graph.baidu.com/resource/" . $obj->data->sign . '.' . $ext;
			return msg(0, '上传成功！', array(
				'imgUrl' => $pic
			));
		}
	}
	
	private function randIp() {
		return mt_rand(0, 255) . '.' . mt_rand(0, 255) . '.' . mt_rand(0, 255) . '.' . mt_rand(0, 255);
	}
	
	private function Curl_POST($url, $post_data) {
		$header = array(
			'X-FORWARDED-FOR:' . $this->randIp(),
			'CLIENT-IP:' . $this->randIp()
		);
		$ch     = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_NOBODY, false);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, false);
		curl_setopt($ch, CURLOPT_TIMEOUT, 30);
		curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
		curl_setopt($ch, CURLOPT_AUTOREFERER, true);
		curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36"); // 伪造ua
		curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
		curl_setopt($ch, CURLOPT_ENCODING, '');
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
		$data = curl_exec($ch);
		curl_close($ch);
		return $data;
	}
}